<template>
  <div class="borrow-management">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2 class="page-title">
        <el-icon><Reading /></el-icon>
        借阅管理
      </h2>
      <div class="header-stats">
        <div class="stat-item">
          <span class="stat-label">总申请</span>
          <span class="stat-value">{{ borrowList.length }}</span>
        </div>
        <div class="stat-item">
          <span class="stat-label">待审核</span>
          <span class="stat-value pending">{{ pendingCount }}</span>
        </div>
        <div class="stat-item">
          <span class="stat-label">已批准</span>
          <span class="stat-value approved">{{ approvedCount }}</span>
        </div>
      </div>
    </div>

    <!-- 搜索和筛选区域 -->
    <div class="filter-section">
      <div class="filter-row">
        <el-input
            v-model="searchQuery"
            placeholder="搜索书名或借阅人"
            style="width: 280px"
            clearable
            @input="handleSearch"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>

        <el-select v-model="statusFilter" placeholder="筛选状态" style="width: 150px" @change="handleFilter">
          <el-option label="全部状态" value="" />
          <el-option label="待审核" value="pending" />
          <el-option label="已批准" value="approved" />
          <el-option label="已拒绝" value="rejected" />
        </el-select>

        <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            style="width: 240px"
            @change="handleDateFilter"
        />
      </div>
    </div>

    <!-- 操作工具栏 -->
    <div class="action-toolbar">
      <div class="toolbar-left">
        <el-button type="primary" @click="applyForBorrow">
          <el-icon><Plus /></el-icon>
          申请借阅
        </el-button>
        <el-button
            type="success"
            :disabled="!selectedItems.length"
            @click="handleBatchApprove"
        >
          <el-icon><Check /></el-icon>
          批量批准
        </el-button>
        <el-button
            type="danger"
            :disabled="!selectedItems.length"
            @click="handleBatchReject"
        >
          <el-icon><Close /></el-icon>
          批量拒绝
        </el-button>
      </div>
      <div class="toolbar-right">
        <el-button @click="refreshData">
          <el-icon><Refresh /></el-icon>
          刷新
        </el-button>
      </div>
    </div>

    <!-- 数据表格 -->
    <div class="table-container">
      <el-table
          :data="filteredBorrowList"
          @selection-change="handleSelectionChange"
          stripe
          :loading="loading"
          empty-text="暂无数据"
          style="width: 100%"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="ID" width="80" sortable />
        <el-table-column prop="bookName" label="书名" min-width="200">
          <template #default="scope">
            <div class="book-info">
              <el-icon class="book-icon"><Reading /></el-icon>
              <span class="book-name">{{ scope.row.bookName }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="userName" label="借阅人" width="120">
          <template #default="scope">
            <div class="user-info">
              <el-icon class="user-icon"><User /></el-icon>
              <span>{{ scope.row.userName }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag
                :type="getStatusTag(scope.row.status)"
                effect="light"
                round
            >
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="borrowTime" label="申请日期" width="120" sortable />
        <el-table-column prop="returnDate" label="归还日期" width="120">
          <template #default="scope">
            <span v-if="scope.row.returnTime">{{ scope.row.returnTime }}</span>
            <span v-else class="text-muted">未归还</span>
          </template>
        </el-table-column>
        <el-table-column prop="borrowDays" label="借阅天数" width="100">
          <template #default="scope">
            <el-tag size="small" type="info">{{ scope.row.borrowDays }}天</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <div class="action-buttons">
              <el-button
                  v-if="scope.row.status === 0"
                  size="small"
                  type="success"
                  @click="approveBorrow(scope.row)"
              >
                <el-icon><Check /></el-icon>
                批准
              </el-button>
              <el-button
                  v-if="scope.row.status === 0"
                  size="small"
                  type="danger"
                  @click="rejectBorrow(scope.row)"
              >
                <el-icon><Close /></el-icon>
                拒绝
              </el-button>
              <el-button
                  v-if="scope.row.status === 'approved'"
                  size="small"
                  type="warning"
                  @click="returnBook(scope.row)"
              >
                <el-icon><Back /></el-icon>
                归还
              </el-button>
              <el-button
                  size="small"
                  type="info"
                  @click="viewDetails(scope.row)"
              >
                <el-icon><View /></el-icon>
                详情
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="filteredBorrowList.length"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      />
    </div>

    <!-- 详情对话框 -->
    <el-dialog
        v-model="detailDialogVisible"
        title="借阅详情"
        width="500px"
        :before-close="handleClose"
    >
      <div v-if="selectedBorrow" class="detail-content">
        <div class="detail-item">
          <label>书名：</label>
          <span>{{ selectedBorrow.bookName }}</span>
        </div>
        <div class="detail-item">
          <label>借阅人：</label>
          <span>{{ selectedBorrow.userName }}</span>
        </div>
        <div class="detail-item">
          <label>状态：</label>
          <el-tag :type="getStatusTag(selectedBorrow.status)">
            {{ getStatusText(selectedBorrow.status) }}
          </el-tag>
        </div>
        <div class="detail-item">
          <label>申请日期：</label>
          <span>{{ selectedBorrow.borrowTime }}</span>
        </div>
        <div class="detail-item">
          <label>借阅天数：</label>
          <span>{{ selectedBorrow.borrowDays }}天</span>
        </div>
        <div class="detail-item">
          <label>备注：</label>
          <span>{{ selectedBorrow.remark || '无' }}</span>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="detailDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {computed, onMounted, reactive, ref} from 'vue';
import {ElMessage, ElMessageBox} from 'element-plus';
import {Back, Check, Close, Plus, Reading, Refresh, Search, User, View} from '@element-plus/icons-vue';
import {getBorrow, updateStatus} from "@/api/borrow";
import {assertSourceType} from "@babel/core/lib/config/validation/option-assertions";


const borrowList =ref([])

const fetchBorrow = async () => {
  const user = reactive({
    userName: '',
  })
  try {
    loading.value = true
      borrowList.value = await getBorrow(user)
  } catch (error) {
    ElMessage.error('获取借阅数据失败')
    console.error(error)
  } finally {
    loading.value = false
  }
}



const selectedItems = ref([]);
const searchQuery = ref('');
const statusFilter = ref('');
const dateRange = ref([]);
const loading = ref(false);
const currentPage = ref(1);
const pageSize = ref(10);
const detailDialogVisible = ref(false);
const selectedBorrow = ref(null);

// 计算属性
const filteredBorrowList = computed(() => {
  let filtered = borrowList.value;

  // 搜索过滤
  if (searchQuery.value) {
    filtered = filtered.filter(item =>
        item.bookName.includes(searchQuery.value) ||
        item.borrower.includes(searchQuery.value)
    );
  }

  // 状态过滤
  if (statusFilter.value) {
    filtered = filtered.filter(item => item.status === statusFilter.value);
  }

  // 日期过滤
  if (dateRange.value && dateRange.value.length === 2) {
    const [startDate, endDate] = dateRange.value;
    filtered = filtered.filter(item => {
      const itemDate = new Date(item.borrowTime);
      return itemDate >= startDate && itemDate <= endDate;
    });
  }

  return filtered;
});

const pendingCount = computed(() =>
    borrowList.value.filter(item => item.status === 'pending').length
);

const approvedCount = computed(() =>
    borrowList.value.filter(item => item.status === 'approved').length
);

// 方法
const handleSelectionChange = (selection) => {
  selectedItems.value = selection;
};

const handleSearch = () => {
  currentPage.value = 1;
};

const handleFilter = () => {
  currentPage.value = 1;
};

const handleDateFilter = () => {
  currentPage.value = 1;
};

const applyForBorrow = () => {
  ElMessage.success('申请借阅功能待开发');
};

const approveBorrow = async (row) => {
  try {
    await ElMessageBox.confirm('确认批准此借阅申请？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    });

    row.status = 1;
    console.log(row)
    const borrowData = reactive({
      status: row.status,
      id: row.id
    })
    await updateStatus(borrowData)
    ElMessage.success('批准成功');
  } catch {
    ElMessage.info('已取消批准');
  }
};

const rejectBorrow = async (row) => {
  try {
    await ElMessageBox.confirm('确认拒绝此借阅申请？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    });

    row.status = 2  ;
    ElMessage.success('拒绝成功');
  } catch {
    ElMessage.info('已取消拒绝');
  }
};

const returnBook = async (row) => {
  try {
    await ElMessageBox.confirm('确认归还此书籍？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    });

    row.returnDate = new Date().toISOString().split('T')[0];
    ElMessage.success('归还成功');
  } catch {
    ElMessage.info('已取消归还');
  }
};

const handleBatchApprove = async () => {
  try {
    await ElMessageBox.confirm(`确认批准选中的 ${selectedItems.value.length} 项申请？`, '批量批准', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    });

    selectedItems.value.forEach(item => {
      if (item.status === 'pending') {
        item.status = 'approved';
      }
    });

    ElMessage.success('批量批准成功');
  } catch {
    ElMessage.info('已取消批量批准');
  }
};

const handleBatchReject = async () => {
  try {
    await ElMessageBox.confirm(`确认拒绝选中的 ${selectedItems.value.length} 项申请？`, '批量拒绝', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    });

    selectedItems.value.forEach(item => {
      if (item.status === 'pending') {
        item.status = 'rejected';
      }
    });

    ElMessage.success('批量拒绝成功');
  } catch {
    ElMessage.info('已取消批量拒绝');
  }
};

const refreshData = () => {
  loading.value = true;
  setTimeout(() => {
    loading.value = false;
    ElMessage.success('数据刷新成功');
  }, 1000);
};



const viewDetails = (row) => {
  selectedBorrow.value = row;
  detailDialogVisible.value = true;
};

const handleClose = (done) => {
  done();
};

const handleSizeChange = (val) => {
  pageSize.value = val;
};

const handleCurrentChange = (val) => {
  currentPage.value = val;
};

const getStatusText = (status) => {
  const statusMap = {
    0: '待审核',
    1: '已批准',
    2: '已拒绝',
    3: '已还'
  };
  return statusMap[status] || status;
};

const getStatusTag = (status) => {
  const tagMap = {
    0: 'warning',
    1: 'success',
    2: 'danger'
  };
  return tagMap[status] || 'info';
};

onMounted(() => {
  // 组件挂载后的初始化操作
  fetchBorrow()
});
</script>

<style scoped>
.borrow-management {
  padding: 24px;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  min-height: 100vh;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding: 20px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.page-title {
  display: flex;
  align-items: center;
  gap: 12px;
  margin: 0;
  font-size: 24px;
  font-weight: 600;
  color: #2c3e50;
}

.header-stats {
  display: flex;
  gap: 24px;
}

.stat-item {
  text-align: center;
  padding: 8px 16px;
  border-radius: 8px;
  background: #f8f9fa;
}

.stat-label {
  display: block;
  font-size: 12px;
  color: #6c757d;
  margin-bottom: 4px;
}

.stat-value {
  display: block;
  font-size: 20px;
  font-weight: 600;
  color: #2c3e50;
}

.stat-value.pending {
  color: #e6a23c;
}

.stat-value.approved {
  color: #67c23a;
}

.filter-section {
  margin-bottom: 20px;
  padding: 20px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}

.filter-row {
  display: flex;
  gap: 16px;
  align-items: center;
  flex-wrap: wrap;
}

.action-toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 16px 20px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}

.toolbar-left, .toolbar-right {
  display: flex;
  gap: 12px;
}

.table-container {
  background: white;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  margin-bottom: 20px;
}

.book-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.book-icon {
  color: #409eff;
}

.book-name {
  font-weight: 500;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 6px;
}

.user-icon {
  color: #67c23a;
}

.action-buttons {
  display: flex;
  gap: 4px;
  flex-wrap: wrap;
}

.text-muted {
  color: #909399;
  font-style: italic;
}

.pagination-container {
  display: flex;
  justify-content: center;
  padding: 20px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}

.detail-content {
  padding: 20px 0;
}

.detail-item {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
  padding: 8px;
  border-radius: 6px;
  background: #f8f9fa;
}

.detail-item label {
  width: 100px;
  font-weight: 600;
  color: #2c3e50;
  margin-right: 12px;
}

.detail-item span {
  flex: 1;
  color: #495057;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .borrow-management {
    padding: 16px;
  }

  .page-header {
    flex-direction: column;
    gap: 16px;
    align-items: flex-start;
  }

  .header-stats {
    width: 100%;
    justify-content: space-around;
  }

  .action-toolbar {
    flex-direction: column;
    gap: 16px;
  }

  .toolbar-left, .toolbar-right {
    width: 100%;
    justify-content: center;
  }

  .filter-row {
    flex-direction: column;
    align-items: stretch;
  }

  .filter-row > * {
    width: 100% !important;
  }
}

/* 动画效果 */
.el-table__row {
  transition: all 0.3s ease;
}

.el-table__row:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

/* 自定义按钮样式 */
.el-button {
  transition: all 0.3s ease;
  border-radius: 8px;
}

.el-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

/* 标签样式优化 */
.el-tag {
  font-weight: 500;
  border: none;
}

/* 输入框样式 */
.el-input__wrapper {
  border-radius: 8px;
}

.el-select .el-select__wrapper {
  border-radius: 8px;
}
</style>